
# Author:: krdlab
class Context
  attr_accessor :req, :res

  def initialize(req, res, parts)
    @req  = req
    @res = res
    @parts = parts
    @rhtml_response = true
  end

  def method_missing(name, *args)
    if name.to_s =~ /(.+)=$/ then
      # self.param= argument なら自動で追加
      add_attr($1, *args)
    else
      super
    end
  end

  def post?
    @req.request_method.downcase == 'post'
  end

  def login?
    _v = nil
    @req.cookies.each {|c|
      _v = c.value; break if c.name == 'demoruby.ticket'
    }
    not _v.blank?
  end

  def app_name
    @parts[:app_name]
  end
  def action
    @parts[:action]
  end
  def action=(name)
    @parts[:action] = name
  end

  def path_args
    @parts[:args]
  end
  class UnsupportedOperationError < StandardError
  end
  def path_args=(*arg)
    raise UnsupportedOperationError.new
  end

  def add_attr(symbol, value=nil)
    self.instance_eval %{
      def #{symbol}
        @#{symbol}
      end
      def #{symbol}=(value)
        @#{symbol} = value
      end
    }
    self.__send__("#{symbol}=", value)
  end

  def rhtml_response=(value)
    @rhtml_response = value
  end

  def rhtml_response?
    @rhtml_response
  end
end

